package com.example.aicompositiongrader;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.example.aicompositiongrader.model.CompositionResponse;
import com.google.gson.Gson;
import java.util.List;

public class ResultActivity extends AppCompatActivity {
    private static final String TAG = "ResultActivity";
    private TextView tvOriginalText;
    private TextView tvCorrections;
    private TextView tvSuggestions;
    private TextView tvOverallComment;
    private TextView tvReferenceEssay;
    private Button buttonContinue;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        initViews();

        // 获取并解析批改结果
        String responseJson = getIntent().getStringExtra("response");
        if (responseJson != null && !responseJson.isEmpty()) {
            try {
                CompositionResponse response = new Gson().fromJson(responseJson, CompositionResponse.class);
                if (response != null) {
                    bindDataToModules(response);
                } else {
                    showError("无法解析批改结果");
                }
            } catch (Exception e) {
                Log.e(TAG, "解析错误", e);
                showError("解析错误: 请重试");
            }
        } else {
            showError("未接收到批改内容");
        }
    }

    private void initViews() {
        tvOriginalText = findViewById(R.id.tvOriginalText);
        tvCorrections = findViewById(R.id.tvCorrections);
        tvSuggestions = findViewById(R.id.tvSuggestions);
        tvOverallComment = findViewById(R.id.tvOverallComment);
        tvReferenceEssay = findViewById(R.id.tvReferenceEssay);
        buttonContinue = findViewById(R.id.buttonContinue);

        // 设置继续批改按钮点击事件
        buttonContinue.setOnClickListener(v -> {
            Intent intent = new Intent(ResultActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });

        // 为文本视图设置滚动属性，避免内容过长无法显示
        setTextViewScrollable(tvOriginalText);
        setTextViewScrollable(tvCorrections);
        setTextViewScrollable(tvSuggestions);
        setTextViewScrollable(tvOverallComment);
        setTextViewScrollable(tvReferenceEssay);
    }

    // 设置TextView可滚动
    private void setTextViewScrollable(TextView textView) {
        textView.setMovementMethod(android.text.method.ScrollingMovementMethod.getInstance());
        textView.setHorizontallyScrolling(false);
    }

    private void bindDataToModules(CompositionResponse response) {
        // 1. 绑定学生原文（添加标题，增强空值保护）
        String originalText = response.getOriginalText();
        String originalTextWithTitle = "【学生原文】\n" +
                (originalText != null && !originalText.equals("无") ? originalText : "无原文内容");
        tvOriginalText.setText(originalTextWithTitle);

        // 2. 绑定基础纠错（添加标题）
        List<CompositionResponse.Correction> corrections = response.getCorrections();
        StringBuilder correctionBuilder = new StringBuilder("【基础纠错】\n\n");
        if (corrections != null && !corrections.isEmpty()) {
            for (int i = 0; i < corrections.size(); i++) {
                CompositionResponse.Correction correction = corrections.get(i);

                // 为空字段设置默认值
                String errorType = correction.getErrorType() != null ? correction.getErrorType() : "未知错误类型";
                String original = correction.getOriginalText() != null ? correction.getOriginalText() : "无原文片段";
                String corrected = correction.getCorrectedText() != null ? correction.getCorrectedText() : "无修改建议";
                String reason = correction.getReason() != null ? correction.getReason() : "无原因说明";

                correctionBuilder.append(i + 1).append(". ")
                        .append("错误类型：").append(errorType).append("\n")
                        .append("原文：").append(original).append("\n")
                        .append("修改为：").append(corrected).append("\n")
                        .append("原因：").append(reason).append("\n\n");
            }
            tvCorrections.setText(correctionBuilder.toString().trim());
        } else {
            correctionBuilder.append("未发现明显错误");
            tvCorrections.setText(correctionBuilder.toString());
        }

        // 3. 绑定优化建议（添加标题）
        List<String> suggestions = response.getOptimizationSuggestions();
        StringBuilder suggestionBuilder = new StringBuilder("【优化建议】\n\n");
        if (suggestions != null && !suggestions.isEmpty()) {
            for (int i = 0; i < suggestions.size(); i++) {
                String suggestion = suggestions.get(i) != null ? suggestions.get(i) : "无具体建议内容";
                suggestionBuilder.append(i + 1).append(". ").append(suggestion).append("\n");
            }
            tvSuggestions.setText(suggestionBuilder.toString().trim());
        } else {
            suggestionBuilder.append("暂无优化建议");
            tvSuggestions.setText(suggestionBuilder.toString());
        }

        // 4. 绑定整体评价（优化星级显示颜色）
        CompositionResponse.OverallEvaluation evaluation = response.getOverallEvaluation();
        StringBuilder evalBuilder = new StringBuilder("【整体评价】\n\n");
        if (evaluation != null) {
            // 评分范围保护（确保在1-5之间）
            int themeScore = clampScore(evaluation.getThemeScore());
            int structureScore = clampScore(evaluation.getStructureScore());
            int languageScore = clampScore(evaluation.getLanguageScore());
            int emotionScore = clampScore(evaluation.getEmotionScore());

            // 评价内容空值保护
            String comment = evaluation.getComment() != null ? evaluation.getComment() : "无详细评价内容";

            // 构建带颜色的星级评价
            evalBuilder.append("主题明确性：").append(getColoredStarString(themeScore)).append("\n")
                    .append("结构完整性：").append(getColoredStarString(structureScore)).append("\n")
                    .append("语言表达：").append(getColoredStarString(languageScore)).append("\n")
                    .append("情感真实性：").append(getColoredStarString(emotionScore)).append("\n\n")
                    .append(comment);

            tvOverallComment.setText(evalBuilder.toString());
        } else {
            evalBuilder.append("暂无评价内容");
            tvOverallComment.setText(evalBuilder.toString());
        }

        // 5. 绑定参考范文（添加标题，确保与原文区分）
        String referenceEssay = response.getReferenceEssay();
        String referenceWithTitle = "【参考范文】\n" +
                (referenceEssay != null && !referenceEssay.equals("无") ? referenceEssay : "无参考范文");
        tvReferenceEssay.setText(referenceWithTitle);
    }

    // 限制评分在1-5的有效范围内
    private int clampScore(int score) {
        if (score < 1) return 1;
        if (score > 5) return 5;
        return score;
    }

    // 生成带颜色的星级字符串（★为黄色，☆为灰色）
    private SpannableString getColoredStarString(int score) {
        String starString = "";
        for (int i = 1; i <= 5; i++) {
            starString += (i <= score ? "★" : "☆");
        }

        SpannableString spannable = new SpannableString(starString);
        int yellowColor = ContextCompat.getColor(this, R.color.star_yellow);
        int grayColor = ContextCompat.getColor(this, R.color.star_gray);

        for (int i = 0; i < 5; i++) {
            int color = (i < score) ? yellowColor : grayColor;
            spannable.setSpan(new ForegroundColorSpan(color),
                    i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return spannable;
    }

    private void showError(String message) {
        tvOriginalText.setText("错误提示：" + message);
        tvCorrections.setText("");
        tvSuggestions.setText("");
        tvOverallComment.setText("");
        tvReferenceEssay.setText("");
    }
}
